package com.newlink.building.activities.main.settings.fragments

import android.content.Context
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import androidx.databinding.DataBindingUtil
import androidx.databinding.ViewDataBinding
import androidx.lifecycle.ViewModelProvider
import com.newlink.building.BR
import com.newlink.building.NL_App
import com.newlink.building.R
import com.newlink.building.activities.main.settings.Module_Phone_SettingListenerStub
import com.newlink.building.activities.main.settings.viewmodels.Module_Phone_AudioCodecViewModel
import com.newlink.building.activities.navigateToEmptySetting
import com.newlink.building.databinding.SettingsAudioCodecFragmentBinding
import com.newlink.building.utils.Module_Phone_ToastUtils
import com.newlink.building.widget.Module_Phone_CustomAlertDialog
import org.linphone.core.tools.Log

/**
 * @Author: Jake
 * @Date: 2022/12/20
 * @Description:
 */
class Module_Phone_AudioCodecSettingsFragment : Module_Phone_GenericSettingFragment<SettingsAudioCodecFragmentBinding>() {

    var mViewModel: Module_Phone_AudioCodecViewModel? = null

    override fun getLayoutId(): Int = R.layout.settings_audio_codec_fragment

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        mViewModel = ViewModelProvider(this)[Module_Phone_AudioCodecViewModel::class.java]

        binding.apply {

            lifecycleOwner = viewLifecycleOwner
            viewModel = mViewModel

            setBackClickListener {
                goBack()
            }

            setSaveClickListener {
                Log.e("jake", "是否改变: " + checkPreferenceChanged())
                if (checkPreferenceChanged()) {
                    savePreferenceChanged()
                    Module_Phone_ToastUtils.showTextToast(context!!, "保存成功")
                } else {
                    Module_Phone_ToastUtils.showTextToast(context!!, "No item need save")
                }
            }
        }
        initAudioCodecsList()
        initTmpValue()
    }

    override fun goBack() {
        Log.e("jake", "返回是否改变: " + checkPreferenceChanged())
        if (checkPreferenceChanged()) {
            showPreferenciesChangedDialog(context!!)
            return
        }
        exitPage()
    }

    private fun initAudioCodecsList() {
        val list = arrayListOf<ViewDataBinding>()
        for ((index, payload)
        in NL_App.coreContext.core.audioPayloadTypes.withIndex()) {
//            if (payload.mimeType.equals("opus") ||
//                payload.mimeType.equals("PCMU") ||
//                payload.mimeType.equals("PCMA") ||
//                payload.mimeType.equals("G722") ||
//                payload.mimeType.equals("iLBC")
//            ) {

            val binding = DataBindingUtil.inflate<ViewDataBinding>(
                LayoutInflater.from(requireContext()),
                R.layout.settings_widget_switch_with_subtitle,
                null,
                false
            )
            binding.setVariable(BR.title, payload.mimeType)
            binding.setVariable(BR.subtitle, "${payload.clockRate} Hz")
            binding.setVariable(BR.checked, payload.enabled())
            binding.setVariable(
                BR.listener,
                object : Module_Phone_SettingListenerStub() {
                    override fun onBoolValueChanged(newValue: Boolean) {
                        list11[index] = newValue
                    }
                }
            )
            binding.lifecycleOwner = viewLifecycleOwner

            list11[index] = payload.enabled()
            list.add(binding)
//            }
        }

//        list.remove(list.get(list.size - 1))
        mViewModel!!.audioCodecs.value = list
    }

    private fun initTmpValue() {
        for (iKey in list11.keys) {
            list22[iKey] = list11[iKey] as Boolean
        }
    }

    private fun savePreferenceChanged() {
        for ((index, payload) in NL_App.coreContext.core.audioPayloadTypes.withIndex()) {
//            if (payload.mimeType.equals("opus") ||
//                payload.mimeType.equals("PCMU") ||
//                payload.mimeType.equals("PCMA") ||
//                payload.mimeType.equals("G722") ||
//                payload.mimeType.equals("iLBC")
//            ) {
            Log.e("jake", "  save ::: $index -->  ${list11[index]}")
            payload.enable(list11[index]!!)
            list22[index] = list11[index]!!
//            }
        }
    }

    private fun checkPreferenceChanged(): Boolean {
        return list11 != list22
    }

//    private fun checkPreferenceChanged2(): Boolean {
//        return !listsEqual(list1, list2)
//    }

    private fun listsEqual(list1: List<Any>, list2: List<Any>): Boolean {

        if (list1.size != list2.size)
            return false
        val pairList = list1.zip(list2)
        return pairList.all { (elt1, elt2) ->
            elt1 == elt2
        }
    }

    private fun showPreferenciesChangedDialog(context: Context) {

        val dialog = Module_Phone_CustomAlertDialog(context).apply {
            setTitle(R.string.settings_save_warning_title)
            setContentText(resources.getString(R.string.settings_save_warning_content))
            setPositiveButton(resources.getString(R.string.save_dialog_custom)) {
                savePreferenceChanged()
                exitPage()
                this.dismiss()
            }
            setNegativeButton(resources.getString(R.string.cancel_dialog_custom)) {
                exitPage()
                this.dismiss()
            }
        }
        dialog.show()
    }

    private fun exitPage() {
        navigateToEmptySetting()
    }

    val list = arrayListOf<ViewDataBinding>()
    val list11 = mutableMapOf<Int, Boolean>()
    private var list22 = mutableMapOf<Int, Boolean>()
}
